package account

import (
	"strings"

	"gitcode.net/togolife/nfttoken/common"
	"github.com/ethereum/go-ethereum/accounts/keystore"
	"github.com/ethereum/go-ethereum/crypto"
)

var log common.NftLog = common.GetNftLog("account")

func CreateAccount() (string, error) {
	account, err := common.GlobalConf.LocalWallet.NewAccount(common.GlobalConf.SecretWord)
	if err != nil {
		log.LogE("Create new account failed! [%v]", err)
		return "", err
	}
	address := strings.ToLower(account.Address.Hex())
	return address, nil
}

func GetCurrentAccounts() []string {
	accounts := common.GlobalConf.LocalWallet.Accounts()
	var address []string
	for _, addr := range accounts {
		if len(addr.Address.Hex()) > 0 {
			address = append(address, strings.ToLower(addr.Address.Hex()))
		}
	}
	return address
}

func ImportAccount(privateKey string) error {
	if strings.HasPrefix(privateKey, "0x") || strings.HasPrefix(privateKey, "0X") {
		privateKey = privateKey[2:]
	}
	key, err := crypto.HexToECDSA(privateKey)
	if err != nil {
		log.LogE("Decode input private key failed! [%v]", err)
		return err
	}
	_, err = common.GlobalConf.LocalWallet.ImportECDSA(key, common.GlobalConf.SecretWord)
	if err != nil && err != keystore.ErrAccountAlreadyExists {
		log.LogE("Import to keystore failed! [%v]", err)
		return err
	}
	return nil
}
